import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 获取状态码
    const status = 
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    
    // 获取异常响应数据
    let exceptionResponse: any = null;
    
    if (exception instanceof HttpException) {
      exceptionResponse = exception.getResponse();
    }

    // 构建错误响应体
    const responseBody: any = {
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    // 处理异常响应数据
    if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
      // 保留原始消息
      if ('message' in exceptionResponse) {
        responseBody.message = exceptionResponse.message;
      } else {
        responseBody.message = exception instanceof HttpException 
          ? exception.message 
          : '服务器内部错误';
      }
      
      // 保留原始 errors 字段（重要：这是ValidationPipe设置的）
      if ('errors' in exceptionResponse) {
        responseBody.errors = exceptionResponse.errors;
      }
    } else {
      // 如果没有结构化的异常响应，使用简单消息
      responseBody.message = exception instanceof HttpException 
        ? exception.message 
        : '服务器内部错误';
    }

    // 开发环境下返回详细错误信息
    if (process.env.NODE_ENV === 'development') {
      responseBody.error = exception instanceof Error ? exception.stack : '未知错误';
    }

    response.status(status).json(responseBody);
  }
}